//
//  ARLoginViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/26.
//

import UIKit

import SnapKit
import JKSwiftExtension
import AttributedString
import Toast_Swift

class ARLoginViewController: ARBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupUI()
    }
    

   // MARK: - UI
    
    private func setupUI() {
        
        view.addSubview(bgView)
//        view.addSubview(logoView)
        view.addSubview(sloganView)
        
        view.addSubview(fastLoginBtn)
        view.addSubview(appleLoginBtn)
        view.addSubview(selectBox)
        view.addSubview(agreementLabel)
        
        bgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(ARHelper.screenWidth() * (415.0 / 375.0))
        }
//        logoView.snp.makeConstraints { make in
//            make.width.height.equalTo(88)
//            make.centerX.equalToSuperview()
//            make.top.equalTo(bgView).offset(ARHelper.screenHeight() * (327 / 812))
//        }
        sloganView.snp.makeConstraints { make in
            make.width.equalTo(170)
            make.height.equalTo(68)
            make.top.equalTo(bgView.snp.bottom).offset(18)
            make.centerX.equalToSuperview()
        }
        
        fastLoginBtn.snp.makeConstraints { make in
            make.top.equalTo(sloganView.snp.bottom).offset(24)
            make.width.equalTo(262)
            make.height.equalTo(54)
            make.centerX.equalToSuperview()
        }
        
        appleLoginBtn.snp.makeConstraints { make in
            make.top.equalTo(fastLoginBtn.snp.bottom).offset(28)
            make.width.height.centerX.equalTo(fastLoginBtn)
        }
        
        selectBox.snp.makeConstraints { make in
            make.top.equalTo(appleLoginBtn.snp.bottom).offset(48)
            make.left.equalTo(appleLoginBtn)
        }
        agreementLabel.snp.makeConstraints { make in
            make.top.equalTo(selectBox)
            make.left.equalTo(selectBox.snp.right).offset(8)
            make.right.equalTo(appleLoginBtn)
        }
    }
    
    // MARK: - Action
    
    @objc private func fastLoginClick(_ sender: UIButton) {
        
        ARLogManager.logPage(.quicklogin)
        
        _loginFirstStep { [weak self] in
            guard let self = self else {
                return
            }
            
            self.ar.showLoading()
            ARUserManager.shared.fastLogin { [weak self] isSuccess, err in
                self?.ar.hideHUD()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                // 成功
                ARAppLauncher.share.transitionToIndexPage()
            }
        }
    }
    
    @objc private func appleLoginClick(_ sender: UIButton) {
        
        ARLogManager.logPage(.applelogin)
        
        _loginFirstStep { [weak self] in
            guard let self = self else {
                return
            }
            
            self.ar.showLoading()
            ARUserManager.shared.appleLogin { [weak self] isSuccess, err in
                self?.ar.hideHUD()
                if let err = err {
                    
                    if case .userCancelled = err {
                        return
                    }
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                // 成功
                ARAppLauncher.share.transitionToIndexPage()
            }
        }
    }
    
    @objc private func selectBoxClick(_ sender: ARSelectBox) {
        sender.isSelected = !sender.isSelected
    }
    
    private func termOfUse() {
        ARLogManager.logPage(.terms)
        
        ARWebDefine.presentSFVc(ARWebDefine.url.termOfUse.rawValue, at: self)
    }
    
    private func privacyPolicy() {
        ARLogManager.logPage(.privacy)
        
        ARWebDefine.presentSFVc(ARWebDefine.url.privacyPolicy.rawValue, at: self)
    }
    
    private func _loginFirstStep(_ completion: @escaping () -> Void) {
        if selectBox.isSelected {
            completion()
            return
        }
        let vc = ARLoginAgreementAlert()
        vc.agreeCallback = { [weak self] in
            guard let self = self else {
                return
            }
            self.selectBoxClick(self.selectBox)
            completion()
        }
        present(vc, animated: true)
    }
    
    // MARK: - Lazy
    
    private lazy var bgView: UIImageView = {
        let image = UIImage(named: "login_top_bg")
        let view = UIImageView.init(image: image)
        view.contentMode = .scaleToFill
        return view
    }()
    
//    private lazy var logoView: UIImageView = {
//        let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "logo.png", ofType: nil) ?? "")
//        let view = UIImageView.init(image: image)
//        view.contentMode = .scaleToFill
//        return view
//    }()
    
    private lazy var sloganView: UIImageView = {
        let view = UIImageView.init(image: .init(named: "login_slogan"))
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var fastLoginBtn: UIButton = {
        let btn = UIButton.ar.themeStyleButton(height: 54, font: ARHelper.font(16, weight: .regular))
        btn.addTarget(self, action: #selector(fastLoginClick(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Fast Login"), for: .normal)
        
        // 图片
        let logoView = UIImageView(image: .init(named: "login_fast"))
        btn.addSubview(logoView)
        logoView.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(32)
        }
        
        return btn
    }()
    
    private lazy var appleLoginBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(appleLoginClick(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Sign in with Apple"), for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        
//        // bgimg
        btn.setBackgroundImage(UIImage.jk.image(color: .init(hexString: "#0D1701")!), for: .normal)
        btn.layer.cornerRadius = 12
        btn.layer.masksToBounds = true
        
        // 图片
        let logoView = UIImageView(image: .init(named: "login_apple"))
        btn.addSubview(logoView)
        logoView.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(32)
        }
        
        return btn
    }()
    
    private lazy var selectBox: ARSelectBox = {
        let view = ARSelectBox()
        view.addTarget(self, action: #selector(selectBoxClick(_:)), for: .touchUpInside)
        return view
    }()
    
    private lazy var agreementLabel: UILabel = {
        //By using our App you agree with our  Term of Use  and Privacy Policy.
        let label = UILabel()
        label.numberOfLines = 0
        
        var str: ASAttributedString = .init(string: ARHelper.localString("By using our App you agree with our\n"), .font(ARHelper.font(12, weight: .regular)), .foreground(.init(hexString: "#505050") ?? .black))
        str += ASAttributedString.init(string: ARHelper.localString("Term of Use"), .font(ARHelper.font(12, weight: .regular)), .foreground(.init(hexString: "#4DB4FF") ?? .black), .underline(.single, color: .init(hexString: "#4DB4FF")), .action { [weak self] in
            self?.termOfUse()
        })
        str += ASAttributedString.init(string: ARHelper.localString("  and "), .font(ARHelper.font(12, weight: .regular)), .foreground(.init(hexString: "#505050") ?? .black))
        str += ASAttributedString.init(string: ARHelper.localString("Privacy Policy."), .font(ARHelper.font(12, weight: .regular)), .foreground(.init(hexString: "#4DB4FF") ?? .black), .underline(.single, color: .init(hexString: "#4DB4FF")), .action { [weak self] in
            self?.privacyPolicy()
        })

        label.attributed.text = "\(wrap: str, .paragraph(.alignment(.left), .lineSpacing(5)))"
        label.lineBreakMode = .byWordWrapping
        
        return label
    }()
    
}
